/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program.gui;

import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import program.beans.Category;
import program.database.Database;

/**
 *
 * Responsible: Patrick, Bernhard
 */
public class ShowCategoriesDlg extends javax.swing.JDialog {

    private Category selectedCategory;
    private Vector<Category> allCategories = new Vector<>();
    private Vector<Category> shownCategories = new Vector<>();
    private Database db = Database.getDatabase();
    
    /**
     * Creates new form ShowCategoriesDlg
     */
    public ShowCategoriesDlg(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setSize(225,300);
        setLocationRelativeTo(null);
        setResizable(false);
        setSize(400,300);
        initList(-1);
    }
    
    /**
     * Read all categories from database and store them into the caollections 
     * Show them on the GUI
     * Select the right category in list
     * 
     * @param selectedIndex The index of the item which should be selected
     */
    private void initList(int selectedIndex) {
        allCategories.clear();
        shownCategories.clear();
        try {
            allCategories.addAll(db.getAllCategories());
        } catch (Exception ex) {
                       JOptionPane.showMessageDialog(null, ex);

        }
        shownCategories.addAll(allCategories);

        if(shownCategories.size() > 0)
         selectedCategory = ( selectedIndex == -1) ? shownCategories.firstElement() : getSelectedCategory(selectedIndex);
        liCategories.setListData(allCategories);
        liCategories.setSelectedValue(selectedCategory, false);
        tfSelectedCategory.setText("");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        tfSelectedCategory = new javax.swing.JTextField();
        pnCenter = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        liCategories = new javax.swing.JList();
        pnButtons = new javax.swing.JPanel();
        btAdd = new javax.swing.JButton();
        btChange = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();
        pnBottom = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        btFinish = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Kategorien");

        tfSelectedCategory.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                onUpdateList(evt);
            }
        });
        getContentPane().add(tfSelectedCategory, java.awt.BorderLayout.NORTH);

        pnCenter.setLayout(new java.awt.BorderLayout());

        liCategories.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        liCategories.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onSelectItem(evt);
            }
        });
        jScrollPane1.setViewportView(liCategories);

        pnCenter.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pnButtons.setLayout(new java.awt.GridBagLayout());

        btAdd.setText("hinzufügen");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onAddCategory(evt);
            }
        });
        pnButtons.add(btAdd, new java.awt.GridBagConstraints());

        btChange.setText("bearbeiten");
        btChange.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onEditCategory(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        pnButtons.add(btChange, gridBagConstraints);

        btDelete.setText("entfernen");
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onDeleteCategory(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        pnButtons.add(btDelete, gridBagConstraints);

        pnCenter.add(pnButtons, java.awt.BorderLayout.LINE_END);

        getContentPane().add(pnCenter, java.awt.BorderLayout.CENTER);

        pnBottom.setLayout(new java.awt.BorderLayout());

        jPanel6.setLayout(new java.awt.GridBagLayout());

        btFinish.setText("Fertig");
        btFinish.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onFinish(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        jPanel6.add(btFinish, gridBagConstraints);

        pnBottom.add(jPanel6, java.awt.BorderLayout.EAST);

        getContentPane().add(pnBottom, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Add category event 
     * Call a dialog to find out the name of the new category
     * Store the new category in database 
     * Reinitialize list
     * 
     * @param evt
     */
    private void onAddCategory(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onAddCategory
        TextInputDlg dlg = new TextInputDlg(this, true, "Kategorie hinzufügen", "");
        dlg.setVisible(true);
        if (dlg.isOk()) {
            int selectedIndex = 0;
            try {
                selectedIndex = db.addCategory(dlg.getText());
            } catch (Exception ex) {
                Logger.getLogger(ShowCategoriesDlg.class.getName()).log(Level.SEVERE, null, ex);
            }
            initList(selectedIndex);
        }
        tfSelectedCategory.requestFocusInWindow();
    }//GEN-LAST:event_onAddCategory

    /**
     * Edit category event
     * Call a dialog to find out the new name of the selected category 
     * Update the edited category in database 
     * Reinitialize list
     * 
     * @param evt
     */
    private void onEditCategory(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onEditCategory
        if (!shownCategories.isEmpty()) {
            TextInputDlg dlg = new TextInputDlg(this, true, "Kategorie bearbeiten", selectedCategory.getDescription());
            dlg.setVisible(true);
            if (dlg.isOk()) {
                try {
                    db.editCategory(new Category(selectedCategory.getId(), dlg.getText()));
                } catch (Exception ex) {
                    Logger.getLogger(ShowCategoriesDlg.class.getName()).log(Level.SEVERE, null, ex);
                }
                initList(selectedCategory.getId());
            }
            tfSelectedCategory.requestFocusInWindow();
        } else {
            JOptionPane.showMessageDialog(this, "Keine Kategorie ausgewählt!");
        }
    }//GEN-LAST:event_onEditCategory

    /**
     * Delete category event
     * Delete the selected category in database 
     * Reinitialize list
     * 
     * @param evt
     */
    private void onDeleteCategory(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onDeleteCategory
        if (!shownCategories.isEmpty()) {
            try {
                db.deleteCategory(selectedCategory.getId());
            } catch (Exception ex) {
                Logger.getLogger(ShowCategoriesDlg.class.getName()).log(Level.SEVERE, null, ex);
            }
            initList(-1);
            tfSelectedCategory.requestFocusInWindow();
        } else {
            JOptionPane.showMessageDialog(this, "Keine Kategorie ausgewählt!");
        }
    }//GEN-LAST:event_onDeleteCategory

    /**
     * Finish event 
     * Sets dialog-control-variable false
     * 
     * @param evt
     */
    private void onFinish(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onFinish
        dispose();
    }//GEN-LAST:event_onFinish

    /**
     * KeyReleased event for the textfield (which is always focused) 
     * If Key is Enter, call ok event 
     * If Key is Esc, call cancel event 
     * If Key is Up, select item above in list
     * If Key is Down, select item below in list 
     * Else retreive the items which fit to the entry in the textfield
     * 
     * @param evt
     */
    private void onUpdateList(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_onUpdateList
        if (evt.getKeyCode() == 10 || evt.getKeyCode() == 27) { // Enter or Esc
            onFinish(null);
        } else if (evt.getKeyCode() == 38) { // Up
            int index = shownCategories.indexOf(selectedCategory);
            index = index > 0 ? index - 1 : index;
            selectedCategory = shownCategories.elementAt(index);
        } else if (evt.getKeyCode() == 40) { // Down
            int index = shownCategories.indexOf(selectedCategory);
            index = index < shownCategories.size() - 1 ? index + 1 : index;
            selectedCategory = shownCategories.elementAt(index);
        } else {
            String curEntry = tfSelectedCategory.getText();
            shownCategories.clear();
            if (curEntry.length() == 0) {
                shownCategories.addAll(allCategories);
            } else {
                for (Category c : allCategories) {
                    if (compare(c.getDescription(), curEntry)) {
                        shownCategories.add(c);
                    }
                }

                if (!shownCategories.isEmpty() && !selectedCategory.isIn(shownCategories)) {
                    selectedCategory = shownCategories.firstElement();
                }
            }
            liCategories.setListData(shownCategories);
        }
        liCategories.setSelectedValue(selectedCategory, false);
    }//GEN-LAST:event_onUpdateList

    /**
     * Mouse event for the list 
     * Change the selected item
     * 
     * @param evt
     */
    private void onSelectItem(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onSelectItem
        selectedCategory = (Category) liCategories.getSelectedValue();
        tfSelectedCategory.requestFocusInWindow();
    }//GEN-LAST:event_onSelectItem

    /**
     * Check if stringPart is similar to the first or all letters of wholeString
     * 
     * @param wholeString The string in which the other string should be
     * @param stringPart The string which should be similar to the first or all letters of wholeString
     * @return True if the stringPart is similar to the first or all letters of wholeString
     */
    private boolean compare(String wholeString, String stringPart) {
        if (stringPart.length() > wholeString.length()) {
            return false;
        }
        for (int i = 0; i < stringPart.length(); i++) {
            if (Character.toLowerCase(stringPart.charAt(i)) != Character.toLowerCase(wholeString.charAt(i))) {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns category with the delivered category id
     * 
     * @param cid category-id for category which will be returned
     * @return category with the delivered id
     */
    private Category getSelectedCategory(int cid) {
        for (Category c : shownCategories) {
            if (c.getId() == cid) {
                return c;
            }
        }
        return null;
    }

    /**
     * Returns selected category for the parent component
     * 
     * @return The selected company
     */
    public Category getCategory() {
        return selectedCategory;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ShowCategoriesDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ShowCategoriesDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ShowCategoriesDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ShowCategoriesDlg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ShowCategoriesDlg dialog = new ShowCategoriesDlg(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btChange;
    private javax.swing.JButton btDelete;
    private javax.swing.JButton btFinish;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList liCategories;
    private javax.swing.JPanel pnBottom;
    private javax.swing.JPanel pnButtons;
    private javax.swing.JPanel pnCenter;
    private javax.swing.JTextField tfSelectedCategory;
    // End of variables declaration//GEN-END:variables
}
